<template>
    <div>
        <el-container direction="vertical">
            <div style="margin: 10px;"></div>
            <el-header style="padding-bottom: 20px;">
                <el-row type="flex" justify="space-between">
                    <el-col :span="3" style="padding: 0;">
                        <span style="font-size: 30px;">人员信息</span>
                    </el-col>
                    <el-col :span="13" style="padding: 0; ">
                        <el-row type="flex" justify="space-between">
                            <el-select clearable placeholder="姓名" v-model="SelectColumn">
                                <el-option v-for="(title, index) in tableTitles" :key="index" :label="title" :value="title">
                                </el-option>
                            </el-select>
                            <el-input placeholder="请输入" v-model="InputKeyWord" @keyup.enter.native="search"
                                clearable></el-input>
                            <el-select clearable placeholder="部门" v-model="selectedDepartment"
                                @change="handleDepartmentChange">
                                <el-option v-for="(department, index) in uniqueDepartments" :key="index" :label="department"
                                    :value="department">
                                </el-option>
                            </el-select>
                        </el-row>
                    </el-col>
                    <el-col :span="1"></el-col>
                    <el-col :span="4">
                        <el-button style="margin-right: 0" type="primary" icon="el-icon-search"
                            @click="search">搜索</el-button>
                        <!-- <el-button type="info"  style="margin: 0; background-color: white; color: black;" @click="viewRouter">可视化</el-button> -->
                    </el-col>
                    <el-col :span="4">
                        <el-button type="primary" style="margin-right:0 ;" @click="change">添加</el-button>
                        <el-button type="danger" style="margin-left: 0;" @click="deleteByIds">删除</el-button>
                    </el-col>
                </el-row>
            </el-header>
            <el-main style="margin-bottom: 20px;">
                <el-table :cell-style="{ textAlign: 'center' }" :header-cell-style="{ textAlign: 'center' }"
                    :data="employeeListLocal" style="width: 100%" :border="true" :fit="true"
                    @selection-change="handleSelectionChange" @sort-change="onSortChange"
                    :default-sort = "{prop: 'employeeNumber', order: 'ascending'}">
                    <el-table-column type="selection" width="55" prop="id">
                    </el-table-column>
                    <el-table-column type="index" width="50">
                    </el-table-column>

                    <el-table-column prop="name" label="姓名">
                    </el-table-column>
                    <el-table-column prop="employeeNumber" sortable label="工号">

                    </el-table-column>
                    <el-table-column prop="departmentName" sortable label="部门">
                    </el-table-column>
                    <el-table-column prop="username" sortable label="用户名">
                    </el-table-column>

                    <el-table-column prop="tel" label="通讯">
                    </el-table-column>
                    <el-table-column prop="gender" label="性别">
                    </el-table-column>
                    <el-table-column width="100">
                        <template slot-scope="scope">
                            <el-button type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </el-main>
            <el-footer style="display: flex; justify-content: center; align-items: center;">
                <el-row type="flex" justify="space-between">

                    <el-pagination :current-page="pageNum" :page-size="pageSize" :page-sizes="pageSizeList" background
                        layout="total, sizes, prev, pager, next, jumper" :total="employeeList.length"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">

                    </el-pagination>

                </el-row>
            </el-footer>
        </el-container>

        <el-dialog :title="title" :visible.sync="dialogVisible" @close="resetDialog" width="70%"
            custom-class="dialog-class">
            <el-form :model="employee" status-icon label-width="80px" :rules="rules" ref="ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input v-model="employee.name"></el-input>
                </el-form-item>

                <el-form-item label="工号" prop="employeeNumber" v-if="title !== '添加'">
                    <el-input v-model="employee.employeeNumber"></el-input>
                </el-form-item>

                <el-form-item label="部门" prop="departmentName">
                    <el-select v-model="employee.departmentName" placeholder="请选择">
                        <el-option v-for="(department, index) in uniqueDepartments" :key="index" :label="department"
                            :value="department">

                        </el-option>

                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="employee.username" :disabled="title == '编辑'"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="employee.password" :disabled="title == '编辑'"></el-input>
                </el-form-item>
                <el-form-item label="通讯" prop="tel">
                    <el-input v-model="employee.tel"></el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-radio-group v-model="employee.gender">
                        <el-radio label="男"></el-radio>
                        <el-radio label="女"></el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">

                <div style="display: flex; justify-content: center;">
                    <el-button type="primary" @click="saveEmployee">{{ title == '添加'
                        ? '添加' : '提交' }}</el-button>
                    <el-button @click="dialogVisible = false">取 消</el-button>
                </div>

            </span>
        </el-dialog>
    </div>
</template>

<script>
import { mapState, } from 'vuex';
import pinyin from 'pinyin';

export default {


    // eslint-disable-next-line vue/multi-word-component-names
    // name: "Table",
    data() {

        var checkMobile = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("手机号不可为空"));
            } else {
                if (value !== "") {
                    var reg = /^(?:(?:\+|00)86)?1\d{10}$/;
                    if (!reg.test(value)) {
                        callback(new Error("请输入有效的手机号码"));
                    }
                }
                callback();
            }
        };

        var checkNameExists = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("姓名不可为空"));
            } else {
                if (value !== "") {
                    var reg = /^(?:[\u4e00-\u9fa5·]{2,16})$/
                    if (!reg.test(value)) {
                        callback(new Error("请输入2-6位的有效姓名"));
                    }
                }
                callback();
            }
        };

        var checkPasswordExists = (rule, value, callback) => {dui
            if (value === "") {
                callback(new Error("密码不可为空"));
            } else {
                var reg = /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[!@#$%^&*.()])[0-9a-zA-Z!@#$%^&*.()]{8,16}$/;
                if (!reg.test(value)) {
                    callback(new Error("密码必须包含数字、英文字母、特殊字符，并且长度在8-16之间"));
                } else {
                    callback();
                }
            }
        };
        // 校验手机号
        var checkTelExists = (rule, value, callback) => {
            if (value === "") {
                callback(new Error("手机号不可为空"));
            } else {
                var reg = /^(?:(?:\+|00)86)?1\d{10}$/;
                if (!reg.test(value)) {
                    callback(new Error("请输入有效的手机号码"));
                } else {
                    callback();
                }
            }
        };


        // 校验工号
        var checkEmployeeNumberExists = (rule, value, callback) => {
            var reg = /^\d{4,10}$/; // 匹配只由数字组成的正则表达式
            if (value === "") {
                callback(new Error("工号不可为空"));
            } else {
                if (!reg.test(value)) {
                    callback(new Error("工号由4-10位数字组成"));
                } else {
                    callback();
                }
            }

        };

        var checkUsernameExists = (rule, value, callback) => {
            if (value === "") {
                callback(new Error('请输入用户名'));
            } else {
                const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]{2,17}$/;
                if (reg.test(value)) {
                    let exists = this.employeeListLocal.some(employee => employee.username === value);
                    if (exists) {
                        callback(new Error('已包含相同账号'));
                    } else {
                        callback();
                    }
                } else {
                    callback(new Error('请输入正确用户名'));
                }
            }
        };



        return {
            employee: {},
            rules: {
                name: [
                    { validator: checkNameExists, required: true, trigger: 'blur' },
                ],
                employeeNumber: [
                    { required: false, validator: checkEmployeeNumberExists, trigger: 'blur' },
                ],

                departmentName: [
                    { required: true, message: '请选择部门', trigger: 'blur' },
                ],
                username: [
                    { validator: checkUsernameExists, required: true, trigger: 'blur' },
                ],
                password: [
                    { required: true, validator: checkPasswordExists, trigger: 'blur' },

                ],
                tel: [
                    { required: true, validator: checkMobile, trigger: 'blur' },

                ],
                gender: [
                    { required: true, message: '请输入性别', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ]
            },
            columnMapping: { '姓名': 'name', '工号': 'employeeNumber', '部门': 'departmentName', '用户名': 'username', '通讯': 'tel', '性别': 'gender' },
            tableTitles: ['姓名', '工号', '用户名', '通讯', '性别'],
            //部门列表
            uniqueDepartments: [],
            SelectColumn: '',
            InputKeyWord: '',
            dialogVisible: false,
            dialogType: '',


            //加载状态
            isLoading: false,
            //删除功能传递给后端的ids
            multipleSelection: [],
            //本地数据
            employeeListLocal: [],

            employeeListOriginal: [],
            //选中的部门
            selectedDepartment: '',
            //每页数据条数
            pageSize: 10,
            //页数
            pageNum: 1,
            pageSizeList: [5, 10, 15],
            total: 0,
            title: '',
            isDialogChangeCount: -1,//判断表单是否修改
        }
    },
    methods: {
        // getChartType(char) {
        //     const chartTypeMap = [
        //         { regex: /^[0-9]$/, type: ["number", 1] },
        //         { regex: /^[a-zA-Z]$/, type: ["en", 2] },
        //         { regex: /^[\u4e00-\u9fa5]$/, type: ["zh", 3] },
        //     ];

        //     for (let i = 0; i < chartTypeMap.length; i++) {
        //         if (chartTypeMap[i].regex.test(char)) {
        //             return chartTypeMap[i].type;
        //         }
        //     }

        //     return ["others", 4];
        // },

        // sortChars(chars) {
        //     return chars.sort((a, b) => {
        //         const [typeA, priorityA] = this.getChartType(a);
        //         const [typeB, priorityB] = this.getChartType(b);

        //         if (priorityA !== priorityB) {
        //             return priorityA - priorityB;
        //         }

        //         switch (typeA) {
        //             case "number":
        //                 return a - b;
        //             case "en":
        //                 return a.localeCompare(b);
        //             case "zh":
        //             // const pinyinA = pinyin(a, {
        //             //         style: pinyin.STYLE_NORMAL,
        //             //         heteronym: false
        //             //     })[0][0];
        //             //     const pinyinB = pinyin(b, {
        //             //         style: pinyin.STYLE_NORMAL,
        //             //         heteronym: false
        //             //     })[0][0];
        //             //     return pinyinA.localeCompare(pinyinB);
        //             default:
        //                 return 0;
        //         }
        //     });
        // },



        onSortChange({ prop, order }) {
            switch (prop) {
                case "departmentName":
                    this.employeeListLocal = this.employeeListLocal.sort((a, b) => order === "ascending" ? this.scoreDepartmentName(a, b) : this.scoreDepartmentName(b, a));
                    console.log("departmentName")
                    break;
                case "employeeNumber":
                    this.employeeListLocal = this.employeeListLocal.sort((a, b) => order === "ascending" ? this.scoreEmployeeNumber(a, b) : this.scoreEmployeeNumber(b, a));
                    console.log("employeeNumber")
                    break;
                case "username":
                    this.employeeListLocal = this.employeeListLocal.sort((a, b) => order === "ascending" ? this.scoreUsername(a, b) : this.scoreUsername(b, a));
                    console.log("username")

                    break;
                default:
                    break;
            }
        },
        scoreDepartmentName(a, b) {
            return a.departmentName.localeCompare(b.departmentName);

        },
        // 获取 a 和 b 在排序顺序对象中的值，并进行比较
        scoreEmployeeNumber(a, b) {
            let numA = parseInt(a.employeeNumber);
            let numB = parseInt(b.employeeNumber);
            // 比较转换后的整数值
            if (numA < numB) {
                return -1;
            } else if (numA > numB) {
                return 1;
            } else {
                return 0;
            }
        },

        scoreUsername(a, b) {
            return a.username.localeCompare(b.username);
        },

        //通过部门查询数据
        handleDepartmentChange(value) {
            this.employeeListLocal = this.employeeList.filter(employee => employee.departmentName === value);
        },
        //删除
        async deleteByIds() {
            this.$confirm('是否确认删除', '信息', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                let result = await this.$store.dispatch('deleteByIds', this.multipleSelection);
                this.pageNum = 1;
                if (result != 200) {
                    this.$message({
                        type: 'error',
                        message: '删除失败',
                        center: true,
                    });
                } else {
                    let deletedData = this.multipleSelection.map(item => JSON.stringify(item)).join(', '); // Convert each item to a string
                    this.$message({
                        type: 'success',
                        message: `删除成功，删除的数据id是：${deletedData}`
                    });
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },

        //条数改变时触发的方法
        handleSizeChange(val) {
            //改变每页显示条数
            this.pageSize = val;
            // 每次变换单页条数后，将页面切换至第一页
            this.pageNum = 1
            // 获取第一页数据
            this.handleCurrentChange(1)
        },
        //页数改变时触发的方法
        handleCurrentChange(val) {
            //改变当前页数据
            this.pageNum = val;
            this.employeeListLocal = this.employeeListOriginal.slice((this.pageNum - 1) * this.pageSize, this.pageNum * this.pageSize);

        },



        //点击添加按钮改变dialog状态
        change() {
            this.title = '添加',
                this.dialogType = 'add';
            this.dialogVisible = true;
        },
        async saveEmployee() {
            this.isLoading = true;
            try {
                let result;
                if (this.dialogType === 'add') {
                    result = await this.$store.dispatch('addEmployee', this.employee);
                    if (result == 200) { // 检查操作是否成功
                        this.$message({
                            type: 'success',
                            duration: 1000,
                            center: true,
                            customClass: 'message-z-index'
                        });
                        setTimeout(this.refresh, 1000);
                    } else {
                        this.$message({
                            message: '操作失败',
                            duration: 1000,
                            center: true,
                            customClass: 'message-z-index'
                        });
                    }
                } else if (this.dialogType === 'edit') {
                    result = await this.$store.dispatch('updateEmployee', this.employee);
                    console.log(this.isDialogChange)
                    if (!this.isDialogChange) {
                        this.$message({
                            message: '请修改数据',
                            duration: 1000,
                            center: true,
                            customClass: 'message-z-index'
                        });

                    } else {
                        if (result == 200) { // 检查操作是否成功
                            this.$message({
                                type: 'success',
                                duration: 1000,
                                center: true,
                                customClass: 'message-z-index'
                            });
                            setTimeout(this.refresh, 1000);

                        } else {
                            this.$message({
                                message: '操作失败',
                                duration: 1000,
                                center: true,
                                customClass: 'message-z-index'
                            });
                        }
                    }


                }

            } catch (error) {
                console.error(error.data);
            } finally {
                this.isLoading = false;
                this.dialogVisible = false;
                this.isDialogChangeCount = -1;
            }
        },

        //重置dialog状态
        resetDialog() {
            this.dialogType = '';
            this.employee = {};
            this.dialogVisible = false;
            this.title = '';
            this.$refs.ruleForm.clearValidate();
        },
        //编辑
        openEditDialog(row) {
            this.title = '编辑',
                this.dialogType = 'edit';
            this.dialogVisible = true;
            this.employee = { ...row };
        },
        //删除
        async deleteEmployee(row) {
            try {
                await this.$store.dispatch('deleteEmployee', row);
                this.$message({
                    message: '删除成功',
                    type: 'success',
                    duration: 1000,
                    center: true,
                });
            } catch (error) {
                this.$message({
                    message: '删除失败',
                    type: 'error',
                    duration: 2000,
                    center: true,
                });
            }
        },
        //发送选中的id到后台
        handleSelectionChange(selectedRows) {
            //将selectedRows的id字段拿出来赋值给multipleSelection
            this.multipleSelection = selectedRows.map(row => row.id);
        },


        search() {
            if (this.SelectColumn === '' || this.InputKeyWord === '') {
                this.$message({
                    message: '请选择搜索条件并输入关键字',
                    type: 'warning'
                });
                return;
            }
            //我要通过SelectColumn的值来找到对应的key并结合InputKeyWord来进行搜索
            let columnValue = this.columnMapping[this.SelectColumn];
            if (this.selectedDepartment !== '') {
                console.log(this.selectedDepartment);
                // 如果部门被选中，就添加一个过滤条件
                this.employeeListLocal = this.employeeList.filter(employee =>
                    employee[columnValue].includes(this.InputKeyWord) && employee.departmentName === this.selectedDepartment);
            } else {
                this.employeeListLocal = this.employeeList.filter(employee => employee[columnValue].includes(this.InputKeyWord));
            }
            // this.SelectColumn = '';
            // this.InputKeyWord = '';
            // this.selectedDepartment = '';
        },
        refresh() {
            this.isLoading = true;
            location.reload();
            this.isLoading = false;

        },

        //获取部门列表
        getuniqueDepartments() {
            let brandList = this.employeeList;
            let departmentSet = new Set();
            for (let i = 0; i < brandList.length; i++) {
                departmentSet.add(brandList[i].departmentName);
            }
            this.uniqueDepartments = Array.from(departmentSet);
        },
    },
    mounted() {
        this.$store.dispatch('employeelist').then(() => {
            this.getuniqueDepartments();
        });
    },
    computed: {
        ...mapState({
            employeeList: state => state.table.employeelist,
        }),
        isDialogChange() {
            return this.isDialogChangeCount > 1;
        }

    },

    created() {
        window.myData = this;//将变量全局化,这样浏览器可以查看当前data是什么情况::myData._data
    },

    watch: {
        employeeList: {
            handler(newVal) {
                this.employeeListOriginal = [...newVal];
                this.employeeListLocal = this.employeeListOriginal.slice(0, this.pageSize);
            },
            immediate: true
        },
        employee: {
            handler(val) {
                if (val) {

                    this.$set(this, 'isDialogChangeCount', this.isDialogChangeCount + 1);
                    console.log('isDialogChangeCount:', this.isDialogChangeCount);
                }
            },
            deep: true,
            immediate: true
        }

    }
}
</script>

<style lang="less" >
.el-message .el-message__icon {
    display: flex;
    justify-content: center;
}

.message-z-index {
    z-index: 3000;
}

.dialog-class {
    //距离顶部5px
    top: 30px;
    /* Adjust this value to change the position */
}
</style>